<template>
  <view class="recharge-page">
    <!-- 当前余额 -->
    <view class="balance-card">
      <view class="balance-info">
        <text class="balance-label">当前余额</text>
        <text class="balance-amount">¥{{ formatMoney(userStore.balance) }}</text>
      </view>
      <view class="balance-icon">💰</view>
    </view>
    
    <!-- 充值金额选择 -->
    <view class="amount-section">
      <text class="section-title">选择充值金额</text>
      
      <view class="amount-grid">
        <view 
          v-for="amount in rechargeAmounts" 
          :key="amount.value"
          class="amount-item" 
          :class="{ selected: selectedAmount === amount.value }"
          @click="selectAmount(amount.value)"
        >
          <text class="amount-value">¥{{ amount.value }}</text>
          <text v-if="amount.bonus" class="amount-bonus">送{{ amount.bonus }}元</text>
          <text v-if="amount.popular" class="amount-tag">热门</text>
        </view>
      </view>
      
      <!-- 自定义金额 -->
      <view class="custom-amount">
        <text class="custom-label">自定义金额</text>
        <view class="custom-input-wrapper">
          <text class="currency-symbol">¥</text>
          <input 
            class="custom-input" 
            type="number" 
            v-model="customAmount"
            placeholder="输入金额"
            @input="onCustomAmountInput"
          />
        </view>
      </view>
    </view>
    
    <!-- 优惠活动 -->
    <view class="promotion-section">
      <text class="section-title">充值优惠</text>
      
      <view class="promotion-list">
        <view class="promotion-item">
          <view class="promotion-icon">🎁</view>
          <view class="promotion-content">
            <text class="promotion-title">首次充值双倍奖励</text>
            <text class="promotion-desc">首次充值100元以上，额外赠送等额积分</text>
          </view>
        </view>
        
        <view class="promotion-item">
          <view class="promotion-icon">⭐</view>
          <view class="promotion-content">
            <text class="promotion-title">会员专享折扣</text>
            <text class="promotion-desc">VIP会员充值享受5%额外奖励</text>
          </view>
        </view>
        
        <view class="promotion-item">
          <view class="promotion-icon">🎯</view>
          <view class="promotion-content">
            <text class="promotion-title">累计充值奖励</text>
            <text class="promotion-desc">单月累计充值满500元，赠送50元代金券</text>
          </view>
        </view>
      </view>
    </view>
    
    <!-- 支付方式 -->
    <view class="payment-section">
      <text class="section-title">支付方式</text>
      
      <view class="payment-methods">
        <view 
          v-for="method in paymentMethods" 
          :key="method.id"
          class="payment-item" 
          :class="{ selected: selectedPayment === method.id }"
          @click="selectPayment(method.id)"
        >
          <view class="payment-info">
            <text class="payment-icon">{{ method.icon }}</text>
            <view class="payment-details">
              <text class="payment-name">{{ method.name }}</text>
              <text class="payment-desc">{{ method.description }}</text>
            </view>
          </view>
          <view class="payment-radio" :class="{ checked: selectedPayment === method.id }">
            <view v-if="selectedPayment === method.id" class="radio-dot"></view>
          </view>
        </view>
      </view>
    </view>
    
    <!-- 充值须知 -->
    <view class="notice-section">
      <text class="section-title">充值须知</text>
      
      <view class="notice-content">
        <text class="notice-item">• 充值金额实时到账，可立即使用</text>
        <text class="notice-item">• 余额不设有效期，长期有效</text>
        <text class="notice-item">• 充值记录可在个人中心查看</text>
        <text class="notice-item">• 如有问题请联系客服：400-123-4567</text>
      </view>
    </view>
    
    <!-- 底部操作栏 -->
    <view class="bottom-actions safe-area-inset-bottom">
      <view class="amount-summary">
        <view class="summary-row">
          <text class="summary-label">支付金额</text>
          <text class="summary-amount">¥{{ finalAmount.toFixed(2) }}</text>
        </view>
        <view v-if="bonusAmount > 0" class="summary-row bonus">
          <text class="summary-label">赠送金额</text>
          <text class="summary-amount">+¥{{ bonusAmount.toFixed(2) }}</text>
        </view>
        <view v-if="bonusAmount > 0" class="summary-row total">
          <text class="summary-label">实际到账</text>
          <text class="summary-amount">¥{{ totalReceiveAmount.toFixed(2) }}</text>
        </view>
      </view>

      <button
        class="recharge-btn"
        :disabled="!canRecharge"
        :class="{ disabled: !canRecharge, loading: recharging }"
        @click="confirmRecharge"
      >
        <view v-if="recharging" class="loading-icon"></view>
        <text class="btn-text">{{ recharging ? '充值中...' : '立即充值' }}</text>
      </button>
    </view>
  </view>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useUserStore } from '@/stores/user'
import { formatMoney, showError, showSuccess, showLoading, hideLoading, showConfirm } from '@/utils/common'

const userStore = useUserStore()

// 响应式数据
const selectedAmount = ref(0)
const customAmount = ref('')
const selectedPayment = ref('wechat')
const recharging = ref(false)

// 充值金额选项
const rechargeAmounts = ref([
  { value: 50, bonus: 0, popular: false },
  { value: 100, bonus: 10, popular: true },
  { value: 200, bonus: 25, popular: false },
  { value: 500, bonus: 80, popular: false },
  { value: 1000, bonus: 200, popular: false },
  { value: 2000, bonus: 500, popular: false }
])

// 支付方式
const paymentMethods = ref([
  {
    id: 'wechat',
    name: '微信支付',
    description: '推荐使用，安全便捷',
    icon: '💬'
  },
  {
    id: 'alipay',
    name: '支付宝',
    description: '支持花呗分期付款',
    icon: '🅰️'
  },
  {
    id: 'bank',
    name: '银行卡',
    description: '支持各大银行储蓄卡',
    icon: '💳'
  }
])

// 计算属性
const finalAmount = computed(() => {
  if (customAmount.value) {
    return parseFloat(customAmount.value) || 0
  }

  const selected = rechargeAmounts.value.find(item => item.value === selectedAmount.value)
  return selected ? selected.value : 0
})

const bonusAmount = computed(() => {
  if (customAmount.value) {
    return 0
  }

  const selected = rechargeAmounts.value.find(item => item.value === selectedAmount.value)
  return selected ? (selected.bonus || 0) : 0
})

const totalReceiveAmount = computed(() => {
  return finalAmount.value + bonusAmount.value
})

const canRecharge = computed(() => {
  const hasValidAmount = selectedAmount.value > 0 || (customAmount.value && parseFloat(customAmount.value) >= 10)
  const hasPaymentMethod = selectedPayment.value
  const notRecharging = !recharging.value

  console.log('canRecharge check:', {
    hasValidAmount,
    hasPaymentMethod,
    notRecharging,
    selectedAmount: selectedAmount.value,
    customAmount: customAmount.value,
    selectedPayment: selectedPayment.value
  })

  return hasValidAmount && hasPaymentMethod && notRecharging
})

// 方法
const selectAmount = (amount) => {
  selectedAmount.value = amount
  customAmount.value = ''
}

const selectPayment = (paymentId) => {
  selectedPayment.value = paymentId
}

const onCustomAmountInput = () => {
  if (customAmount.value) {
    selectedAmount.value = 0
  }
}

const confirmRecharge = async () => {
  if (!canRecharge.value) return

  const amount = customAmount.value ? parseFloat(customAmount.value) : selectedAmount.value

  if (amount < 10) {
    showError('最低充值金额为10元')
    return
  }

  if (amount > 10000) {
    showError('单次充值金额不能超过10000元')
    return
  }

  const confirmed = await showConfirm(`确认充值 ¥${amount.toFixed(2)} 吗？`)
  if (!confirmed) return

  recharging.value = true
  showLoading('充值中...')

  try {
    // 模拟支付流程 - 增加更真实的支付步骤
    console.log('开始充值流程:', { amount, paymentMethod: selectedPayment.value })

    // 第一步：创建支付订单
    await new Promise(resolve => setTimeout(resolve, 800))
    console.log('支付订单创建成功')

    // 第二步：调用支付接口
    await new Promise(resolve => setTimeout(resolve, 1200))
    console.log('调用支付接口')

    // 第三步：支付结果处理
    await new Promise(resolve => setTimeout(resolve, 1000))
    console.log('处理支付结果')

    // 模拟支付成功 - 提高成功率到95%
    const success = Math.random() > 0.05

    if (success) {
      // 计算实际到账金额（包含奖励）
      const actualAmount = totalReceiveAmount.value

      console.log('充值成功:', {
        payAmount: amount,
        bonusAmount: bonusAmount.value,
        actualAmount
      })

      // 直接使用addBalance方法增加余额
      const balanceAdded = userStore.addBalance(actualAmount, '充值')

      if (balanceAdded) {
        // 奖励积分（按支付金额计算，不包含奖励）
        const points = Math.floor(amount)
        userStore.addPoints(points, '充值奖励')

        // 首次充值额外奖励检查
        const isFirstRecharge = userStore.totalSpent <= actualAmount
        if (isFirstRecharge && amount >= 100) {
          const firstRechargeBonus = Math.floor(amount * 0.1) // 10%额外积分
          userStore.addPoints(firstRechargeBonus, '首次充值奖励')
          showSuccess(`充值成功！获得${points + firstRechargeBonus}积分奖励（含首次充值奖励）${bonusAmount.value > 0 ? `，赠送${bonusAmount.value}元` : ''}`)
        } else {
          showSuccess(`充值成功！获得${points}积分奖励${bonusAmount.value > 0 ? `，赠送${bonusAmount.value}元` : ''}`)
        }

        // 重置表单
        selectedAmount.value = 0
        customAmount.value = ''

        // 延迟返回
        setTimeout(() => {
          uni.navigateBack()
        }, 2000)
      } else {
        throw new Error('余额更新失败')
      }
    } else {
      throw new Error('支付失败')
    }
  } catch (error) {
    console.error('充值失败:', error)
    showError(error.message || '充值失败，请重试')
  } finally {
    recharging.value = false
    hideLoading()
  }
}

// 生命周期
onMounted(() => {
  if (!userStore.isLoggedIn) {
    uni.showModal({
      title: '请先登录',
      content: '充值功能需要先登录账户',
      confirmText: '去登录',
      success: (res) => {
        if (res.confirm) {
          uni.navigateTo({
            url: '/pages/login/login'
          })
        } else {
          uni.navigateBack()
        }
      }
    })
  }
})
</script>

<style lang="scss" scoped>
.recharge-page {
  min-height: 100vh;
  background: var(--color-background);
  padding: 16px;
  padding-bottom: 120px;
}

// 余额卡片
.balance-card {
  background: linear-gradient(135deg, var(--color-success), #5ad427);
  border-radius: var(--radius-xl);
  padding: 24px;
  margin-bottom: 24px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  color: white;
  box-shadow: 0 4px 16px rgba(52, 199, 89, 0.3);
}

.balance-info {
  flex: 1;
}

.balance-label {
  font-size: 14px;
  opacity: 0.9;
  display: block;
  margin-bottom: 8px;
}

.balance-amount {
  font-size: 32px;
  font-weight: bold;
}

.balance-icon {
  font-size: 48px;
  opacity: 0.8;
}

// 区域标题
.section-title {
  font-size: 18px;
  font-weight: 600;
  color: var(--color-text-primary);
  margin-bottom: 16px;
  display: block;
}

// 金额选择区域
.amount-section {
  background: white;
  border-radius: var(--radius-xl);
  padding: 20px;
  margin-bottom: 16px;
  box-shadow: var(--shadow-sm);
}

.amount-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 12px;
  margin-bottom: 20px;
}

.amount-item {
  position: relative;
  background: var(--color-background);
  border: 2px solid transparent;
  border-radius: var(--radius-lg);
  padding: 16px 12px;
  text-align: center;
  transition: all var(--transition-normal);

  &.selected {
    border-color: var(--color-primary);
    background: rgba(0, 122, 255, 0.05);
  }

  &:active {
    transform: scale(0.95);
  }
}

.amount-value {
  font-size: 18px;
  font-weight: bold;
  color: var(--color-text-primary);
  display: block;
  margin-bottom: 4px;
}

.amount-bonus {
  font-size: 12px;
  color: var(--color-success);
  display: block;
}

.amount-tag {
  position: absolute;
  top: -6px;
  right: -6px;
  background: var(--color-gaming);
  color: white;
  font-size: 10px;
  padding: 2px 6px;
  border-radius: var(--radius-sm);
}

.custom-amount {
  border-top: 1px solid var(--color-border);
  padding-top: 20px;
  display: flex;
  align-items: center;
  gap: 16px;
}

.custom-label {
  font-size: 16px;
  color: var(--color-text-primary);
  font-weight: 500;
  min-width: 80px;
}

.custom-input-wrapper {
  flex: 1;
  display: flex;
  align-items: center;
  background: var(--color-background);
  border-radius: var(--radius-lg);
  padding: 12px 16px;
  border: 2px solid transparent;
  transition: border-color var(--transition-normal);

  &:focus-within {
    border-color: var(--color-primary);
  }
}

.currency-symbol {
  font-size: 16px;
  color: var(--color-text-secondary);
  margin-right: 8px;
}

.custom-input {
  flex: 1;
  font-size: 16px;
  color: var(--color-text-primary);
  border: none;
  outline: none;
  background: transparent;

  &::placeholder {
    color: var(--color-text-tertiary);
  }
}

// 优惠活动区域
.promotion-section {
  background: white;
  border-radius: var(--radius-xl);
  padding: 20px;
  margin-bottom: 16px;
  box-shadow: var(--shadow-sm);
}

.promotion-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.promotion-item {
  display: flex;
  align-items: flex-start;
  gap: 12px;
  padding: 12px;
  background: var(--color-background);
  border-radius: var(--radius-lg);
}

.promotion-icon {
  font-size: 24px;
  margin-top: 2px;
}

.promotion-content {
  flex: 1;
}

.promotion-title {
  font-size: 16px;
  font-weight: 600;
  color: var(--color-text-primary);
  display: block;
  margin-bottom: 4px;
}

.promotion-desc {
  font-size: 14px;
  color: var(--color-text-secondary);
  line-height: 1.4;
}

// 支付方式区域
.payment-section {
  background: white;
  border-radius: var(--radius-xl);
  padding: 20px;
  margin-bottom: 16px;
  box-shadow: var(--shadow-sm);
}

.payment-methods {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.payment-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16px;
  background: var(--color-background);
  border: 2px solid transparent;
  border-radius: var(--radius-lg);
  transition: all var(--transition-normal);

  &.selected {
    border-color: var(--color-primary);
    background: rgba(0, 122, 255, 0.05);
  }

  &:active {
    transform: scale(0.98);
  }
}

.payment-info {
  display: flex;
  align-items: center;
  gap: 12px;
  flex: 1;
}

.payment-icon {
  font-size: 24px;
}

.payment-details {
  flex: 1;
}

.payment-name {
  font-size: 16px;
  font-weight: 500;
  color: var(--color-text-primary);
  display: block;
  margin-bottom: 2px;
}

.payment-desc {
  font-size: 12px;
  color: var(--color-text-secondary);
}

.payment-radio {
  width: 20px;
  height: 20px;
  border: 2px solid var(--color-border);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all var(--transition-normal);

  &.checked {
    border-color: var(--color-primary);
  }
}

.radio-dot {
  width: 10px;
  height: 10px;
  background: var(--color-primary);
  border-radius: 50%;
}

// 充值须知
.notice-section {
  background: white;
  border-radius: var(--radius-xl);
  padding: 20px;
  margin-bottom: 16px;
  box-shadow: var(--shadow-sm);
}

.notice-content {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.notice-item {
  font-size: 14px;
  color: var(--color-text-secondary);
  line-height: 1.5;
}

// 底部操作栏
.bottom-actions {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background: white;
  padding: 16px;
  border-top: 1px solid var(--color-border);
  display: flex;
  align-items: flex-end;
  gap: 16px;
  box-shadow: 0 -2px 12px rgba(0, 0, 0, 0.08);
}

.amount-summary {
  flex: 1;
}

.summary-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 4px;

  &:last-child {
    margin-bottom: 0;
  }

  &.bonus {
    .summary-amount {
      color: var(--color-success);
    }
  }

  &.total {
    padding-top: 4px;
    border-top: 1px solid var(--color-border);
    margin-top: 4px;

    .summary-label {
      font-weight: 600;
    }

    .summary-amount {
      font-size: 18px;
      font-weight: bold;
      color: var(--color-primary);
    }
  }
}

.summary-label {
  font-size: 14px;
  color: var(--color-text-secondary);
}

.summary-amount {
  font-size: 16px;
  font-weight: 500;
  color: var(--color-text-primary);
}

.recharge-btn {
  background: linear-gradient(135deg, var(--color-primary), var(--color-primary-light));
  color: white;
  border: none;
  border-radius: var(--radius-xl);
  padding: 14px 32px;
  font-size: 16px;
  font-weight: 600;
  display: flex;
  align-items: center;
  gap: 8px;
  box-shadow: 0 4px 12px rgba(0, 122, 255, 0.3);
  transition: all var(--transition-normal);

  &:not(.disabled):not(.loading):active {
    transform: scale(0.95);
  }

  &.disabled {
    background: var(--color-text-tertiary);
    box-shadow: none;
  }
}

.loading-icon {
  width: 16px;
  height: 16px;
  border: 2px solid rgba(255, 255, 255, 0.3);
  border-top-color: white;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  to { transform: rotate(360deg); }
}

.btn-text {
  color: white;
}

// 响应式适配
@media (max-width: 375px) {
  .recharge-page {
    padding: 12px;
    padding-bottom: 120px;
  }

  .balance-card {
    padding: 20px;
  }

  .balance-amount {
    font-size: 28px;
  }

  .balance-icon {
    font-size: 40px;
  }

  .amount-grid {
    grid-template-columns: repeat(2, 1fr);
  }

  .amount-item {
    padding: 14px 10px;
  }

  .amount-value {
    font-size: 16px;
  }

  .custom-amount {
    flex-direction: column;
    align-items: stretch;
    gap: 12px;
  }

  .custom-label {
    min-width: auto;
  }

  .payment-item {
    padding: 12px;
  }

  .payment-name {
    font-size: 15px;
  }

  .summary-amount {
    font-size: 20px;
  }
}
</style>
